package com.hellpro.lolbox.home.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Parcelable;

import com.hellpro.lolbox.bean.ZXZp;
import com.hellpro.lolbox.utils.OkHttpClientUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Package_Name: com.hellpro.lolbox.home.service
 * Description : 如果json中没有图片的宽高，那么我们在得到数据的后为了配合瀑布流，
 * 或者减少系统的测绘工作，开启一个intentSeivice 在service里将流转化成bitmap 进行测绘将
 * 值放入到数据中，在给imageview设置其宽高。
 * author: HellPermanent
 * date:  2016/10/22 10:28
 * remarks：
 */
public class DataService  extends IntentService {
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public DataService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
  if (intent ==null){
      return;
  }
      List<ZXZp.DataBean> dataBeen  = intent.getParcelableArrayListExtra("data");
        String subType = intent.getStringExtra("subType");
        handleSetItenData(dataBeen,subType);
    }

    private void handleSetItenData(List<ZXZp.DataBean> dataBeen, String subType) {
        if (dataBeen.size()==0){
            return;
        }
        for (ZXZp.DataBean data: dataBeen
             ) {
            try {
                byte[] bytes = OkHttpClientUtils.getBytesFromURL(this, data.getCoverUrl(), null);
                if (bytes.length!=0) {
                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                   data.setCoverWidth(String.valueOf(   bitmap.getWidth()));
                    data.setCoverHeight(String.valueOf(bitmap.getHeight()));
                }


            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static  void  startService(Context context, List<ZXZp.DataBean> dataBeen,String subType){
        Intent intent = new Intent(context, DataService.class);
        intent.putParcelableArrayListExtra("data", (ArrayList<? extends Parcelable>) dataBeen);
             intent.putExtra("subType",subType);
        context.startService(intent);
    }





}
